/**
 * BasicHTTPClient.ino
 *
 *  Created on: 24.05.2015
 *
 */

#include <Arduino.h>

#include <WiFi.h>
#include <WiFiMulti.h>
#include <HTTPClient.h>
#define USE_SERIAL Serial
#include <TFT_eSPI.h> //Graphics and font lib for ST7735 driver chip
#include <SPI.h>
#include "Button2.h"
#include "esp_adc_cal.h"
#include <Ticker.h>

#define ADC_EN              14  //ADC_EN is the ADC detection enable port
#define ADC_PIN             34
#define BUTTON_1            35
#define BUTTON_2            0
#define ScreenBackgroundColor TFT_BLACK
WiFiMulti wifiMulti;
TFT_eSPI tft = TFT_eSPI();
Button2 btn1(BUTTON_1);
Button2 btn2(BUTTON_2);
int vref = 1100;
Ticker ticker;
/*
const char* ca = \ 
"-----BEGIN CERTIFICATE-----\n" \  
"MIIEkjCCA3qgAwIBAgIQCgFBQgAAAVOFc2oLheynCDANBgkqhkiG9w0BAQsFADA/\n" \  
"MSQwIgYDVQQKExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMT\n" \  
"DkRTVCBSb290IENBIFgzMB4XDTE2MDMxNzE2NDA0NloXDTIxMDMxNzE2NDA0Nlow\n" \  
"SjELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUxldCdzIEVuY3J5cHQxIzAhBgNVBAMT\n" \  
"GkxldCdzIEVuY3J5cHQgQXV0aG9yaXR5IFgzMIIBIjANBgkqhkiG9w0BAQEFAAOC\n" \  
"AQ8AMIIBCgKCAQEAnNMM8FrlLke3cl03g7NoYzDq1zUmGSXhvb418XCSL7e4S0EF\n" \  
"q6meNQhY7LEqxGiHC6PjdeTm86dicbp5gWAf15Gan/PQeGdxyGkOlZHP/uaZ6WA8\n" \  
"SMx+yk13EiSdRxta67nsHjcAHJyse6cF6s5K671B5TaYucv9bTyWaN8jKkKQDIZ0\n" \  
"Z8h/pZq4UmEUEz9l6YKHy9v6Dlb2honzhT+Xhq+w3Brvaw2VFn3EK6BlspkENnWA\n" \  
"a6xK8xuQSXgvopZ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u0Qg==\n" \  
"-----END CERTIFICATE-----\n";
*/

//string process
//从由separator分隔的原始串中获取第i个子串
String getValueSeparated(String& data, char separator, int index)
{
    int found = 0;
    int strIndex[] = { 0, -1 };
    int maxIndex = data.length() - 1;

    for (int i = 0; i <= maxIndex && found <= index; i++) {
        if (data.charAt(i) == separator || i == maxIndex) {
            found++;
            strIndex[0] = strIndex[1] + 1;
            strIndex[1] = (i == maxIndex) ? i+1 : i;
        }
    }
    return found > index ? data.substring(strIndex[0], strIndex[1]) : "";
}
int stringChrCount(String & s,char c)
{
    int ret = 0;
    for(int i=0;i<s.length();i++)
    {
        if(s[i]==c)ret++;        
    }
    return ret;
}

String getVoltage()
{
  String voltage="";
    static uint64_t timeStamp = 0;
    if (millis() - timeStamp > 1000) {
        timeStamp = millis();
        uint16_t v = analogRead(ADC_PIN);
        float battery_voltage = ((float)v / 4095.0) * 2.0 * 3.3 * (vref / 1000.0);
        voltage = " " + String(battery_voltage) + "V";
    }
    return voltage;
}

void button_init()
{
    btn1.setLongClickHandler([](Button2 & b) {
        int r = digitalRead(TFT_BL);
        digitalWrite(TFT_BL, !r);

        tft.writecommand(TFT_DISPOFF);
        tft.writecommand(TFT_SLPIN);
        //After using light sleep, you need to disable timer wake, because here use external IO port to wake up
        esp_sleep_disable_wakeup_source(ESP_SLEEP_WAKEUP_TIMER);
        // esp_sleep_enable_ext1_wakeup(GPIO_SEL_35, ESP_EXT1_WAKEUP_ALL_LOW);
        esp_sleep_enable_ext0_wakeup(GPIO_NUM_35, 0);
        delay(200);
        esp_deep_sleep_start();
    });
    btn1.setPressedHandler([](Button2 & b) {
        Serial.println("Detect Voltage..");
        
    });

    btn2.setPressedHandler([](Button2 & b) {
        println("btn press wifi scan");
        cls();
        println(getVoltage());
    });
}


void button_loop()
{
    btn1.loop();
    btn2.loop();
}

void setup() {

    USE_SERIAL.begin(115200);

    USE_SERIAL.println();
    USE_SERIAL.println();
    USE_SERIAL.println();


    tft.init();
    tft.setRotation(1);
    tft.fillScreen(TFT_BLACK);
    tft.setTextColor(TFT_YELLOW,TFT_BLACK);
    tft.setTextSize(2);
    tft.setTextWrap(240,135);
    button_init();
    
    tft.setTextColor(TFT_CYAN,TFT_BLACK);
    println("China Stock ");
    tft.setTextSize(2);
    tft.setTextColor(TFT_YELLOW,TFT_BLACK);

    wifiMulti.addAP("ChinaNet-yu", "ydd200706");
    wifiMulti.addAP("comicyu_2f", "67799706100");
    println("Connecting WiFi ...");
    
    if(wifiMulti.run()!=WL_CONNECTED)
    {
    for(uint8_t t = 2; t > 0; t--) {
        USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
        USE_SERIAL.flush();
        delay(1000);
    }
    }    

    ticker.attach(5.0,getData);
    getData();
}

size_t print(const String& x)
{
  Serial.print(x); 
  return tft.print(x); 
  }
  
size_t println(const String& x)
{
  Serial.println(x); 
  return tft.println(x); 
  }

void cls()
{
  tft.fillScreen(ScreenBackgroundColor); 
  tft.setCursor(0,0); 
}


void showInfo(String data)
{
    
    cls();
    
    int itemCount = stringChrCount(data,';');
    for(int i=0;i<itemCount;i++)
    {
        String info = getValueSeparated(data,';',i);
    //name
    tft.setTextColor(TFT_BLUE,TFT_BLACK);
    String name = getValueSeparated(info,'"',0);
    name.replace("var hq_str_sh","");
    name.replace("=",":");
    println(name);

    String s = getValueSeparated(info,'"',1);
    //Serial.println("divided string:");
    //Serial.println(s);
    
    int st =atoi(getValueSeparated(s,',',2).c_str());
    int curr =atoi(getValueSeparated(s,',',3).c_str());
    tft.setTextColor(TFT_ORANGE,TFT_BLACK);
    print(String(st));
    print(" ");
    print(String(curr));
    print(" ");
    print(String(curr-st));
    print(" ");
    print(String((float)(curr-st)*100/(float)st));
    }
}

void getData()
{
    
    USE_SERIAL.println("getting data...");
    if((wifiMulti.run() == WL_CONNECTED)) {
        HTTPClient http;

        USE_SERIAL.print("[HTTP] begin...\n");
        // configure traged server and url
        //http.begin("https://www.howsmyssl.com/a/check", ca); //HTTPS
        //http.begin("http://example.com/index.html"); //HTTP
        http.begin("http://hq.sinajs.cn/list=sh600519,sh000300,sh000001");

        USE_SERIAL.print("[HTTP] GET...\n");
        // start connection and send HTTP header
        int httpCode = http.GET();

        // httpCode will be negative on error
        if(httpCode > 0) {
            // HTTP header has been send and Server response header has been handled
            USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode);

            // file found at server
            if(httpCode == HTTP_CODE_OK) {
                String payload = http.getString();
                USE_SERIAL.println(payload);
                showInfo(payload);
            }
        } else {
            USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
        }

        http.end();
    }
    else
    {
        print ("No connected.");
    }

}

void loop() {
    // wait for WiFi connection
    button_loop();
}
